package com.zxx.otherchaos.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.zxx.otherchaos.MyApplication;
import com.zxx.otherchaos.R;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import androidx.annotation.StringRes;

/**
 * 吐司相关工具类
 *
 * @author zxx on 2020/12/29
 */
public class ToastUtils2 {

    private static Toast sToast;
    private static Handler sHandler = new Handler(Looper.getMainLooper());
    //自定义时长显示
    private static Runnable runnable = new Runnable() {
        @Override
        public void run() {
            sToast.cancel();
        }
    };
    private static boolean isJumpWhenMore;

    private ToastUtils2() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 吐司初始化
     *
     * @param isJumpWhenMore 当连续弹出吐司时，是要弹出新吐司还是只修改文本内容
     *                       {@code true}: 弹出新吐司
     *                       {@code true}: 只修改文本内容
     *                       如果为{@code false}的话可用来做显示任意时长的吐司
     */
    public static void init(boolean isJumpWhenMore) {
        ToastUtils2.isJumpWhenMore = isJumpWhenMore;
    }

    //----------------安全地显示短时吐司--------------------------
    public static void showShortToastSafe(final CharSequence text) {
        sHandler.post(new Runnable() {
            @Override
            public void run() {
                showShortToast(text);
            }
        });
    }

    public static void showShortToastSafe(final @StringRes int resId) {
        String text = getResString(resId);
        showShortToastSafe(text);
    }

    /**
     * 格式化显示
     */
    public static void showShortToastSafe(final @StringRes int resId, final Object... args) {
        String text = getResFormatString(resId, args);
        showShortToastSafe(text);
    }

    /**
     * 安全地显示短时吐司
     */
    public static void showShortToastSafe(final String format, final Object... args) {
        String text = getFormatString(format, args);
        showShortToastSafe(text);
    }

    //-----------------------安全地显示长时吐司-----------------------------
    public static void showLongToastSafe(final CharSequence text) {
        sHandler.post(new Runnable() {
            @Override
            public void run() {
                showLongToast(text);
            }
        });
    }

    /**
     * 安全地显示长时吐司
     */
    public static void showLongToastSafe(final @StringRes int resId) {
        String text = getResString(resId);
        showLongToastSafe(text);
    }

    /**
     * 安全地显示长时吐司
     */
    public static void showLongToastSafe(final @StringRes int resId, final Object... args) {
        String text = getResFormatString(resId, args);
        showLongToastSafe(text);
    }

    /**
     * 安全地显示长时吐司
     */
    public static void showLongToastSafe(final String format, final Object... args) {
        String text = getFormatString(format, args);
        showLongToastSafe(text);
    }

    //----------------------------------------------------------------

    /**
     * 显示短时吐司
     */
    public static void showShortToast(CharSequence text) {
        showToast(text, Toast.LENGTH_SHORT);
    }

    public static void showShortToast(@StringRes int resId) {
        showShortToast(getResString(resId));
    }

    public static void showShortToast(@StringRes int resId, Object... args) {
        showShortToast(getResFormatString(resId, args));
    }

    public static void showShortToast(String format, Object... args) {
        showShortToast(getFormatString(format, args));
    }

    //----------------------------------------------------------------------

    /**
     * 显示长时吐司
     */
    public static void showLongToast(CharSequence text) {
        showToast(text, Toast.LENGTH_LONG);
    }

    public static void showLongToast(@StringRes int resId) {
        showLongToast(getResString(resId));
    }

    public static void showLongToast(@StringRes int resId, Object... args) {
        showLongToast(getResFormatString(resId, args));
    }

    public static void showLongToast(String format, Object... args) {
        showLongToast(getFormatString(format, args));
    }

    //---------------------------自定义--------------------------------------
    public static void showCenterToast(int resId) {
        showCenterToast(getResString(resId));
    }

    public static void showCenterToast(String msg) {
        showCenterToast(msg, Toast.LENGTH_SHORT);
    }

    public static void showCenterToast(String msg, int duration) {
        LayoutInflater inflater = (LayoutInflater) MyApplication.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //自定义布局
        View view = inflater.inflate(R.layout.core_toast_center, null);
        TextView textView = view.findViewById(R.id.toast_msg);
        textView.setText(checkNetWork(msg));

        sHandler.removeCallbacks(runnable);
        show(view, msg, duration);

        if (duration == Toast.LENGTH_SHORT) {
            duration = 1000;
        } else if (duration== Toast.LENGTH_LONG){
            duration = 2000;
        }
        sHandler.postDelayed(runnable, duration);
    }

    //-----------------------------------------------------------------
    private static String getResString(@StringRes int resId) {
        return MyApplication.getContext().getResources().getText(resId).toString();
    }

    private static String getResFormatString(@StringRes int resId, Object... args) {
        return String.format(MyApplication.getContext().getResources().getString(resId), args);
    }

    private static String getFormatString(String format, Object... args) {
        return String.format(format, args);
    }

    private static String checkNetWork(String text) {
        if (!NetWorkUtil.isConnectNet(MyApplication.getContext())) {
            text = "未连接网络";
        }
        return text;
    }

    private static void showToast(CharSequence text, int duration) {
        if (isJumpWhenMore) cancelToast();
        String result = checkNetWork(text.toString());
        show(null, result, duration);
    }

    /**
     * 自定义显示toast
     * 如果把手机设置里的通知关闭，则toast不会显示
     * OPPO 9.0可以显示
     */
    private static void show(View view, CharSequence text, int duration) {
        try {
            if (view == null) {
                if (sToast == null) {
                    sToast = Toast.makeText(MyApplication.getContext(), text, duration);
                } else {
                    sToast.setText(text);
                }
            } else {
                if (sToast == null) {
                    sToast = new Toast(MyApplication.getContext());
                }
                sToast.setGravity(Gravity.CENTER, 0, 0);
                sToast.setView(view);
            }
            sToast.setDuration(duration);
            sToast.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消吐司显示
     */
    public static void cancelToast() {
        if (sToast != null) {
            sToast.cancel();
            sToast = null;
        }
    }

    //----------------------------------------------------------------------------

    // 请注意这段代码强烈建议不要放到实际开发中，因为用户屏蔽通知栏和开启应用状态下的概率极低，可以忽略不计
    public static void showSystemToast(String msg) {
        showShortToast(msg);
        showSystemToast(sToast);
    }

    // 请注意这段代码强烈建议不要放到实际开发中，因为用户屏蔽通知栏和开启应用状态下的概率极低，可以忽略不计
    public static void showSystemToast(Toast toast) {
        try {
            @SuppressLint("SoonBlockedPrivateApi")
            Method serviceMethod = Toast.class.getDeclaredMethod("getService");

            serviceMethod.setAccessible(true);

            final Object iNotificationManager = serviceMethod.invoke(null);
            Class iNotificationManagerCls = Class.forName("android.app.INotificationManager");
            Object iNotificationManagerProxy = Proxy.newProxyInstance(toast.getClass().getClassLoader(),
                    new Class[]{iNotificationManagerCls}, new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            // 强制使用系统Toast
                            // 华为p20 pro上为enqueueToastEx
                            if ("enqueueToast".equals(method.getName()) || "enqueueToastEx".equals(method.getName())) {
                                args[0] = "android";
                            }

                            return method.invoke(iNotificationManager, args);
                        }
                    });

            Field serviceFiled = Toast.class.getDeclaredField("sService");
            serviceFiled.setAccessible(true);
            serviceFiled.set(null, iNotificationManagerProxy);
            toast.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}